package com.bai.ad.service;

import com.alibaba.fastjson.JSON;
import com.bai.ad.ApplicationTest;
import com.bai.ad.constant.CommonStatus;
import com.bai.ad.dao.AdPlanRepository;
import com.bai.ad.dao.AdUnitRepository;
import com.bai.ad.dao.CreativeRepository;
import com.bai.ad.dao.unit_condition.AdUnitDistrictRepository;
import com.bai.ad.dao.unit_condition.AdUnitItRepository;
import com.bai.ad.dao.unit_condition.AdUnitKeywordRepository;
import com.bai.ad.dao.unit_condition.CreativeUnitRepository;
import com.bai.ad.entity.AdPlan;
import com.bai.ad.entity.AdUnit;
import com.bai.ad.entity.Creative;
import com.bai.ad.entity.unit_condition.AdUnitDistrict;
import com.bai.ad.entity.unit_condition.AdUnitIt;
import com.bai.ad.entity.unit_condition.AdUnitKeyword;
import com.bai.ad.entity.unit_condition.CreativeUnit;
import com.bao.ad.dump.Dconstant;
import com.bao.ad.dump.table.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName DumpDataService
 *
 * @author Bai
 * @version 1.0
 * @date 2019/2/28 0028 下午 23:24
 **/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ApplicationTest.class},
        webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class DumpDataService {

    @Autowired
    private AdPlanRepository planRepository;
    @Autowired
    private AdUnitRepository unitRepository;
    @Autowired
    private CreativeRepository creativeRepository;
    @Autowired
    private CreativeUnitRepository creativeUnitRepository;
    @Autowired
    private AdUnitDistrictRepository districtRepository;
    @Autowired
    private AdUnitItRepository itRepository;
    @Autowired
    private AdUnitKeywordRepository keywordRepository;

    @Test
    public void dumpAdTableData() {

        dumpAdPlanTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_PLAN)
        );
        dumpAdUnitTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_UNIT)
        );
        dumpAdCreativeTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_CREATIVE)
        );
        dumpAdCreativeUnitTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_CREATIVE_UNIT)
        );
        dumpAdUnitDistrictTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_UNIT_DISTRICT)
        );
        dumpAdUnitItTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_UNIT_IT)
        );
        dumpAdUnitKeywordTable(
                String.format("%s%s", Dconstant.DATA_ROOT_DIR,
                        Dconstant.AD_UNIT_KEYWORD)
        );
    }
    
    private void dumpAdPlanTable(String fileName){
        List<AdPlan> adPlans = planRepository.findAllByPlanStatus(CommonStatus.VALID.getStatus());

        if(CollectionUtils.isEmpty(adPlans)){
            return;
        }

        ArrayList<AdPlanTable> planTables = new ArrayList<>();
        adPlans.forEach(p -> planTables.add(
                new AdPlanTable(
                        p.getId(),
                        p.getUserId(),
                        p.getPlanStatus(),
                        p.getStartDate(),
                        p.getEndDate()
                )
        ));

        writerTable("dumpAdPlanTable", fileName, planTables);
    }

    private void dumpAdUnitTable(String fileName){
        List<AdUnit> adUnits = unitRepository.findAllByUnitStatus(CommonStatus.VALID.getStatus());
        if(CollectionUtils.isEmpty(adUnits)){
            return;
        }
        List<AdUnitTable> unitTables = new ArrayList<>();
        adUnits.forEach( u -> unitTables.add(
                new AdUnitTable(
                        u.getId(),
                        u.getUnitStatus(),
                        u.getPositionType(),
                        u.getPlanId()
                )
        ));

        writerTable("dumpAdUnitTable", fileName, unitTables);
    }

    private void dumpAdCreativeTable(String fileName) {

        List<Creative> creatives = creativeRepository.findAll();
        if (CollectionUtils.isEmpty(creatives)) {
            return;
        }

        List<AdCreativeTable> creativeTables = new ArrayList<>();
        creatives.forEach(c -> creativeTables.add(
                new AdCreativeTable(
                        c.getId(),
                        c.getName(),
                        c.getType(),
                        c.getMaterialType(),
                        c.getHeight(),
                        c.getWidth(),
                        c.getAuditStatus(),
                        c.getUrl()
                )
        ));

        writerTable("dumpAdCreativeTable", fileName, creativeTables);
    }

    private void dumpAdCreativeUnitTable(String fileName) {

        List<CreativeUnit> creativeUnits = creativeUnitRepository.findAll();
        if (CollectionUtils.isEmpty(creativeUnits)) {
            return;
        }

        List<AdCreativeUnitTable> creativeUnitTables = new ArrayList<>();
        creativeUnits.forEach(c -> creativeUnitTables.add(
                new AdCreativeUnitTable(
                        c.getCreativeId(),
                        c.getUnitId()
                )
        ));

        writerTable("dumpAdCreativeUnitTable", fileName, creativeUnitTables);
    }

    private void dumpAdUnitDistrictTable(String fileName) {

        List<AdUnitDistrict> unitDistricts = districtRepository.findAll();
        if (CollectionUtils.isEmpty(unitDistricts)) {
            return;
        }

        List<AdUnitDistrictTable> unitDistrictTables = new ArrayList<>();
        unitDistricts.forEach(d -> unitDistrictTables.add(
                new AdUnitDistrictTable(
                        d.getUnitId(),
                        d.getProvince(),
                        d.getCity()
                )
        ));

        writerTable("dumpAdUnitDistrictTable", fileName, unitDistrictTables);
    }

    private void dumpAdUnitItTable(String fileName) {

        List<AdUnitIt> unitIts = itRepository.findAll();
        if (CollectionUtils.isEmpty(unitIts)) {
            return;
        }

        List<AdUnitItTable> unitItTables = new ArrayList<>();
        unitIts.forEach(i -> unitItTables.add(
                new AdUnitItTable(
                        i.getUnitId(),
                        i.getItTag()
                )
        ));

        writerTable("dumpAdUnitItTable", fileName, unitItTables);
    }

    private void dumpAdUnitKeywordTable(String fileName) {
        List<AdUnitKeyword> unitKeywords = keywordRepository.findAll();
        if (CollectionUtils.isEmpty(unitKeywords)) {
            return;
        }

        List<AdUnitKeywordTable> unitKeywordTables = new ArrayList<>();
        unitKeywords.forEach(k -> unitKeywordTables.add(
                new AdUnitKeywordTable(
                        k.getUnitId(),
                        k.getKeyword()
                )
        ));

        writerTable("dumpAdUnitItTable", fileName, unitKeywordTables);
    }

    private static<T> void writerTable(String className, String fileName, List<T> tableList){
        Path path = Paths.get(fileName);
        try(BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (T table : tableList){
                writer.write(JSON.toJSONString(table));
                writer.newLine();
            }
        } catch (IOException e){
            log.info(className + " error");
        }
    }
}
